package Leetcode.ArrayAndLinkedList.rotate189;

/**
 * 反转数组法 时间复杂度为O(n)  最优解法
 * 空间复杂度为O(1)
 */
public class Solution2 {
    public void rotate(int[] nums, int k) {
        if (nums == null) {
            return;
        }
        if (nums.length < 2) {
            return;
        }
        k = k % nums.length;

        nums = reverse(nums, 0, nums.length - 1);
        nums = reverse(nums, 0, k - 1);
        nums = reverse(nums, k, nums.length - 1);
    }

    public int[] reverse(int[] nums, int start, int end) {
        int len = (end - start + 1) / 2;
        for (int i = 0; i < len; i++) {
            if (start == end) {
                return nums;
            }
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
        return nums;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4};
        Solution2 solution = new Solution2();
        solution.rotate(nums, 2);
        for (int i : nums) {
            System.out.print(i);
        }
    }
}
